package org.yx.service.sres.save_maintain_items;

import org.yx.exception.BizException;
import org.yx.models.SresMtnDef;
import org.yx.utils.BaseService;
import org.yx.utils.FieldMap;

import com.xiaoleilu.hutool.util.StrUtil;

/**
 * 保存保养项目
 * 
 * @author zxw
 * @since 2019/08/31
 **/
public class SresSaveMaintainItemsService extends BaseService {
	public SresSaveMaintainItemsOut saveMaintainItems(SresSaveMaintainItemsIn in) throws Exception {
		if (StrUtil.isBlank(in.getItemCode())) {
			throw new BizException("SYS-0004", FieldMap.of("parameter", "itemCode"));
		}

		SresMtnDef mtnDef = new SresMtnDef();
		copyProperties(in, mtnDef);
		mtnDef.setOrgCode(in.getUserOrgCode());

		if (mtnDef.getStatus() == null) {
			mtnDef.setStatus('N');
		}

		SresMtnDef oldMtn = selectOneLocked(SresMtnDef.class, mtnDef.getOrgCode(), mtnDef.getItemCode());
		if ((oldMtn != null && oldMtn.getStatus() == 'D') || ('N' != mtnDef.getStatus() && oldMtn == null)) {
			throw new BizException("SRES-0002", "保养项目${itemCode}不存在或已删除。",
					FieldMap.of("itemCode", mtnDef.getItemCode()));
		}

		if ('D' == mtnDef.getStatus()) {
			update(mtnDef, "status");
		} else {
			upsert(mtnDef);
		}

		SresSaveMaintainItemsOut out = new SresSaveMaintainItemsOut();

		return out;
	}
}